package com.aabte.auth.account.infrastructure.messaging.producer;

import com.aabte.auth.account.application.AccountEventPublisher;
import com.aabte.auth.account.domain.event.AccountCreated;
import com.aabte.auth.account.domain.event.PasswordChanged;
import com.aabte.auth.account.domain.model.Account;
import com.aabte.auth.tracker.model.Status;
import com.aabte.auth.tracker.model.Tracker;
import com.aabte.auth.tracker.repository.TrackerRepository;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;

@Component
public class AccountEventPublisherImpl implements AccountEventPublisher {

    @Resource
    private ApplicationContext context;

    @Resource
    private TrackerRepository trackerRepository;

    @Override
    public void accountCreated(Account account) {
        AccountCreated accountCreated = new AccountCreated(account.getAccountId(), account.getAccountName());
        context.publishEvent(accountCreated);

        Tracker tracker = new Tracker(trackerRepository.nextTrackerId(), accountCreated.identity(), Instant.now(),
                null, 0, Status.PROCESSING);
        trackerRepository.store(tracker);
    }

    @Override
    public void passwordChanged(Account account) {
        PasswordChanged passwordChanged = new PasswordChanged(account.getAccountId(), account.getAccountName());
        context.publishEvent(passwordChanged);

        Tracker tracker = new Tracker(trackerRepository.nextTrackerId(), passwordChanged.identity(), Instant.now(),
                null, 0, Status.PROCESSING);
        trackerRepository.store(tracker);
    }
}
